package com.qfmy.app.service.impl.common;

import com.qfmy.app.minio.MinioProperties;
import com.qfmy.app.service.common.FileUploadService;
import io.minio.*;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.novel.impl
 * @date 2025/3/1
 * @description 文件上传
 */
@Service
@SuppressWarnings("all")
public class  FileUploadServiceImpl implements FileUploadService {

    /**
     *注入Minio客户端
     */
    @Resource
    private MinioClient mc;

    /**
     *注入Minio配置文件
     */
    @Resource
    private MinioProperties mp;

    /**
     *生成文件上传
     */
    @Override
    @SneakyThrows
    public String upload(MultipartFile file)  {
        String url = null;
        //判断桶是否存在，不存在则创建
        boolean b = mc.bucketExists(BucketExistsArgs.builder()
                .bucket(mp.getBucketName()).build());
        if (!b) {
            //创建桶
            mc.makeBucket(MakeBucketArgs.builder()
                    .bucket(mp.getBucketName()).build());
            //设置桶策略
            mc.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(mp.getBucketName())
                    .config(BuckerName(mp.getBucketName()))
                    .build());

        }
        //使用UUID生成文件名
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date())
                + "/" + UUID.randomUUID() + "-"
                + file.getOriginalFilename();
        //上传文件
        mc.putObject(PutObjectArgs.builder()
                .bucket(mp.getBucketName())
                .stream(file.getInputStream(),file.getSize(),-1).object(filename)
                //设置文件类型->为了让浏览器不下载直接打开所以要设置文件类型
                .contentType(file.getContentType())
                .build());
        //拼接url
        url = String.join("/",mp.getEndpoint(),mp.getBucketName(),filename);
        return url;
    }

    /**
     *生成桶的名称
     */
    public String BuckerName(String bucketName)
    {
        return """
                  {
                    "Statement" : [ {
                      "Action" : "s3:GetObject",
                      "Effect" : "Allow",
                      "Principal" : "*",
                      "Resource" : "arn:aws:s3:::%s/*"
                    } ],
                    "Version" : "2012-10-17"
                  }
                  """.formatted(bucketName);
    }
}